package com.yxr.affairs;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.beiing.leafchart.OutsideLineChart;
import com.beiing.leafchart.bean.Axis;
import com.beiing.leafchart.bean.AxisValue;
import com.beiing.leafchart.bean.Line;
import com.beiing.leafchart.bean.PointValue;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.BarLineChartTouchListener;
import com.thoughtworks.xstream.XStream;
import com.yxr.affairs.api.Constans1;
import com.yxr.affairs.base.BaseActivity1;
import com.yxr.affairs.utils.Utils;
import com.yxr.affairs.xin.Data;
import com.yxr.affairs.xin.Param1;
import com.yxr.affairs.xin.Storeditem;
import com.yxr.affairs.xtem.EncodeXstream;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.content.Context.MODE_PRIVATE;

public class XinActivity extends BaseActivity1 {

    LineChart mLineChart;
    @BindView(R.id.goback)
    ImageButton goback;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.activity_xuan)
    TextView activityXuan;
    @BindView(R.id.settingrule)
    RelativeLayout settingrule;
    @BindView(R.id.activity_2)
    TextView activity2;
    @BindView(R.id.settin)
    RelativeLayout settin;

//    @BindView(R.id.linechart)
//    OutsideLineChart linechart;

    private   String Honst;
    private  String  time;
    private  int i=6;

    private    String i1s, i2s;

    private int mYear;
    private int mMonth;
    private int mDay;
    ProgressDialog xh_pDialog;
    private int[] mDataLeft;
    private int [] xDate;
    List<AxisValue> axisValues;
    List<Integer> mList = new ArrayList<>();
    private  int [] data;

    private String SoftVersion;
    private String DataServerIP;
    private String Key;
    private String DataServerPort;
    private String SoftName;
    private String mDeviceid;
    private String mUsercode;
    private String mUserpwd;
    private String mVersion;
    private String mHospitalid;
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_xin;
    }

    @Override
    protected void initViews() {


        SharedPreferences sPreferences=getSharedPreferences("muser", MODE_PRIVATE);
        Key=sPreferences.getString("Key", "");
        DataServerIP=sPreferences.getString("DataServerIP", "");
        DataServerPort=sPreferences.getString("DataServerPort", "");
        mDeviceid=sPreferences.getString("mDeviceid", "");
        mUsercode=sPreferences.getString("mUsercode", "");
        mUserpwd=sPreferences.getString("mUserpwd", "");
        mVersion=sPreferences.getString("mVersion", "");
        mHospitalid=sPreferences.getString("mHospitalid", "");

        mLineChart = (LineChart) findViewById(R.id.chart);
        goback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        settin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCode();
            }
        });

        SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
        String cDate = df.format(new Date());
        Calendar c = Calendar.getInstance();
        Date date=null;
        try {
            date = new SimpleDateFormat("yy.MM.dd").parse(cDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day=c.get(Calendar.DATE);
        c.set(Calendar.DATE,day-1);

        String dayBefore=new SimpleDateFormat("yyyy.MM.dd").format(c.getTime());

        activity2.setText(dayBefore);
        time=dayBefore;
        if (!Utils.isNetworkConnected(mContext)) {
            Toast.makeText(mContext, getString(R.string.network_hint), Toast.LENGTH_SHORT).show();
            return;
        }
        QueryAddressTask queryAddressTask = new QueryAddressTask();
        queryAddressTask.execute(Honst, time,  i+"");


     //   initLineChart();
    }

    public void getCode(){

        Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);

        new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {


                if (i1 < 9) {
                    i1s = "0" + (i1 + 1);
                } else {
                    i1s = "" + (i1 + 1);
                }

                if (i2 < 10) {
                    i2s = "0" + i2;
                } else {
                    i2s = "" + i2;
                }

                Log.e("birthId", (i + "" + i1s + "-" + "" + i2));

                activity2.setText(i + "." + i1s + "." + i2s);
                //   activity_2.setText((i +i1s+i2s+mHoure+mInute+mSecond).format("%Y-%m-%d %H:%M:%S"));
                Honst=activity2.getText().toString();
                time=activity2.getText().toString();
                if (!Utils.isNetworkConnected(mContext)) {
                    Toast.makeText(mContext, getString(R.string.network_hint), Toast.LENGTH_SHORT).show();
                    return;
                }
                QueryAddressTask queryAddressTask = new QueryAddressTask();
                queryAddressTask.execute(Honst, time,  i+"");

            }
        }, mYear, mMonth, mDay).show();


        Log.i("birthday2", mYear + "--" + mMonth + "--" + Integer.parseInt(String.valueOf(mDay-1)));
    }


    private String getData(String param){
        String    result = null;
        String WSDL_URI = "http://"+DataServerIP+":"+DataServerPort+"/soap/IHyWebServer";//wsdl 的uri
        String namespace = "urn:HyWebServerIntf-IHyWebServer";//namespace
        String methodName = "HyWebServiceIntfMethod";//要调用的方法名称

        SoapObject request = new SoapObject(namespace, methodName);

        String de= "<hywebserviceroot>" +
                "<funname>GetMbUserFunction</funname>" +
                "<hospitalid>"+mHospitalid+"</hospitalid>" +
                "    <key>"+Key+"</key>" +
                "    <deviceid>"+mDeviceid+"</deviceid>" +
                "    <usercode>"+mUsercode+"</usercode>" +
                "    <userpwd>"+mUserpwd+"</userpwd>" +
                "    <version>"+mVersion+"</version>" +
                "    <params>" +
                "     <param1><sFunName>GetMZGHZRC</sFunName></param1>" +
                "     <param2><dL_RQ>"+time+" 00:00:00"+"</dL_RQ><sHospitalID></sHospitalID><LX>6</LX></param2>"+
                "    </params>" +
                "</hywebserviceroot>";

        request.addProperty("aXml", de);
        //创建SoapSerializationEnvelope 对象，同时指定soap版本号(之前在wsdl中看到的)

        try {
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
            envelope.bodyOut = request;//由于是发送请求，所以是设置bodyOut
            envelope.dotNet = true;//由于是.net开发的webservice，所以这里要设置为true
            HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
            httpTransportSE.debug = false;
            httpTransportSE.call("urn:HyWebServerIntf-IHyWebServer#HyWebServiceIntfMethod", envelope);//调用

            // 获取服务器响应返回的SOAP消息
            SoapObject object = (SoapObject) envelope.bodyIn;
            result = object.getProperty(0).toString();
            //     Log.e("DSDSDS", result);
            return result;

        } catch (Exception e) {
            Log.e("TAG", "getData: "+e );
        }
        return result;

    }
    class QueryAddressTask extends AsyncTask<String, Integer, String> {

        protected void onPreExecute() {
            xh_pDialog = new ProgressDialog(XinActivity.this);

            // 设置进度条风格，风格为圆形，旋转的
            xh_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            xh_pDialog.setTitle("正在加载，请稍等");
            xh_pDialog.setIndeterminate(false);

            // 设置ProgressDialog 是否可以按退回键取消
            xh_pDialog.setCancelable(true);

            // 让ProgressDialog显示
            xh_pDialog.show();

        }

        protected String doInBackground(String... params) {
            // 查询手机号码（段）信息*/
            String result = null;
            String result1 = null;
            try {
                result = getData(params[0]);


            } catch (Exception e) {

                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法

            Log.e("ADDADADggg", result );
            return result + "," + result;
        }

        protected void onPostExecute(String result) {

            xh_pDialog.dismiss();

            if (result != null) {
                XStream xStream2 = new EncodeXstream("1.0", "gb2312");
                xStream2.alias("result", Data.class);
                xStream2.useAttributeFor(Param1.class, "size");
                xStream2.addImplicitCollection(Param1.class, "storeditems");
                xStream2.alias("storeditem", Storeditem.class);
                Data data = (Data) xStream2.fromXML(result);

                Log.e("TAG1", "status: " + data.getStatus());
                Log.e("TAG1", "errorinfo: " + data.getErrorinfo());
                Log.e("TAG1", "successinfo" + data.getSuccessinfo());
                Log.e("TAG1", "param1 size: " + data.getSuccessinfo().getParam1().getSize());


                List<Storeditem> storeditems = data.getSuccessinfo().getParam1().getStoreditems();


                try {

                    mList.clear();
                    for (int j = 0; j < 24; j++) {
                        int bb = -1;
                        if(data.getSuccessinfo().getParam1().getStoreditems() == null){
                           /* if (bb == -1){
                                mList.add(0);
                            }*/

                        }else {
                            for (int k = 0; k < storeditems.size(); k++) {
                                if (j<10){
                                    if (storeditems.get(k).getsType().equals(("0" + j))){
                                        bb = k;
                                    }
                                }else{
                                    if (storeditems.get(k).getsType().equals((String.valueOf(j)))){
                                        bb = k;
                                    }
                                }
                            }
                        }


                        if (bb == -1){
                            mList.add(0);
                        }else{
                            mList.add(Integer.parseInt(storeditems.get(bb).getiSL()));
                        }


                    }
                }catch (Exception e) {

                    e.printStackTrace();
                }
               if(mList.size()!=0){
                   initLineChart();
                   mLineChart.getData().notifyDataChanged();
               }


                for (int i = 0; i < mList.size(); i++) {
                //    array[i] = mList.get(i);
                    System.out.println("array--> " + mList.get(i));
                    Log.e("adasdasd",mList.get(i).toString());
                }
              /*  for (int i = 0; i < array.length; i++) {
                    System.out.println("array--> " + array[i]);

                }*/


             /*   for (Storeditem s : storeditems) {
                    Log.e("TAG1", "patient_id: " + s.getiSL());
                    Log.e("TAG1", "dealno: " + s.getsType());
                    Log.e("TAG1", "billno: " + s.getfZJE());
                    mDataLeft=new int[storeditems.size()];//创建一个和list长度一样的数组
                    for(int i=0;i<storeditems.size();i++){
                        mDataLeft[i]=Integer.parseInt(storeditems.get(i).getiSL());//数组赋值了。
                        Log.e("ADADAAD", String.valueOf(mDataLeft[i]));
                    }

                    for(int j=0;j<storeditems.size();j++){
                        xDate[j]=Integer.parseInt(storeditems.get(j).getsType());
                    }

                    }*/

            }
        }
        }

    private boolean IS_CS = false;
        private void initLineChart(){

        /*//模拟数据
            for (int j = 0; j < 24; j++) {
                mList.add(new Random().nextInt(200));
            }
*/

            //1.设置x轴和y轴的点
            List<Entry> entries = new ArrayList<>();
            for (int i = 0; i < 24; i++)
                entries.add(new Entry(i, mList.get(i)));


            if (IS_CS){
                //2. 获取LineDataSet线条数据集
                List<ILineDataSet> dataSets = mLineChart.getLineData().getDataSets();



                //是否存在
                if (dataSets != null && dataSets.size() > 0) {
                    //直接更换数据源
                    for (ILineDataSet set : dataSets) {
                        LineDataSet data = (LineDataSet) set;
                        data.setValues(entries);
                   //     data.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
                    }
                } else {
                    //重新生成LineDataSet线条数据集
                    LineDataSet dataSet = new LineDataSet(entries, "折线图，人数与时间"); // add entries to dataset
                    dataSet.setDrawCircles(false);
                    dataSet.setColor(Color.parseColor("#7d7d7d"));//线条颜色
                    //   dataSet.setCircleColor(Color.parseColor("#7d7d7d"));//圆点颜色
                    dataSet.setDrawCircles(true);
                    dataSet.setLineWidth(1f);//线条宽度
                    LineData lineData = new LineData(dataSet);
                    //是否绘制线条上的文字
                    lineData.setDrawValues(false);
                    mLineChart.setData(lineData);
                }

                //更新
                mLineChart.invalidate();
            }else{
                IS_CS = true;
                //2.把数据赋值到你的线条
                LineDataSet dataSet = new LineDataSet(entries, "折线图，人数与时间"); // add entries to dataset
                dataSet.setDrawCircles(false);
                dataSet.setColor(Color.parseColor("#FF4081"));//线条颜色
                //  dataSet.setCircleColor(Color.parseColor("#7d7d7d"));//圆点颜色
                dataSet.setDrawCircles(true);
                dataSet.setLineWidth(1f);//线条宽度
                mLineChart.setScaleEnabled(false);

                //mLineChart.getLineData().getDataSets().get(0).setVisible(true);
                //设置样式
                YAxis rightAxis = mLineChart.getAxisRight();
                //设置图表右边的y轴禁用
                rightAxis.setEnabled(false);
                YAxis leftAxis = mLineChart.getAxisLeft();
                //设置图表左边的y轴禁用
                leftAxis.setEnabled(true);
                mLineChart.setAutoScaleMinMaxEnabled(true);
                // leftAxis.resetAxisMaxValue();
                leftAxis.setStartAtZero(true);
                leftAxis.setAxisMinimum(0f);
                leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
              //  leftAxis.setDrawGridLines(false);
      /*  rightAxis.setAxisMaximum(dataSet.getYMax());
        leftAxis.setAxisMaximum(dataSet.getYMax());*/
                //设置x轴
                XAxis xAxis = mLineChart.getXAxis();
                xAxis.setTextColor(Color.parseColor("#333333"));
                xAxis.setTextSize(5f);
                xAxis.setAxisMinimum(0f);
                xAxis.setDrawAxisLine(true);//是否绘制轴线
                xAxis.setDrawGridLines(false);//设置x轴上每个点对应的线
                xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
                xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
                xAxis.setGranularity(1f);//禁止放大x轴标签重绘
//        xAxis.setAxisMaximum(24); // 此轴能显示的最大值；
                xAxis.setLabelCount(24, false); // 纵轴上标签显示的数量,数字不固定。如果force = true,将会画出明确数量，但是可能值导致不均匀，默认（6，false）
                List<String> list = new ArrayList<>();
                for (int i = 0; i < 24; i++) {
                    list.add(i + ":00");
                }
                xAxis.setValueFormatter(new IndexAxisValueFormatter(list));


                //3.chart设置数据
                LineData lineData = new LineData(dataSet);
                //是否绘制线条上的文字
                lineData.setDrawValues(true);
                mLineChart.setData(lineData);
//            mLineChart.invalidate(); // refresh

                //允许左右滑动
                float scaleX = mLineChart.getScaleX();
                if (scaleX == 1)
                    mLineChart.zoomToCenter(1.2f, 1f);
                else {
                    BarLineChartTouchListener barLineChartTouchListener = (BarLineChartTouchListener) mLineChart.getOnTouchListener();
                    barLineChartTouchListener.stopDeceleration();
                    mLineChart.fitScreen();
                }

                mLineChart.invalidate();
            }
        }

        @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (xh_pDialog != null){
            xh_pDialog.dismiss();
            xh_pDialog = null;
        }
    }
    @Override
    protected void onError_(Throwable e) {

    }

    @Override
    protected void onCancel_() {

    }
}
